<?php

namespace app\home\logic;

use app\common\logic\Base;
use think\facade\App;
use think\facade\Env;
use think\facade\Request;

class Index extends  Base {
    
    /**
     * @desc 生成url短链接
     * @param array $params
     * @param int $userId
     * @return array|bool
     */
    public function buildUrl($params, $userId) {
        $request= Request::instance();
        $ip = $request->ip(); //获取客户端IP地址
        $header = $request->header();
        $userAgent = $header['user-agent'];
        
        $keyword = model('Url')->getUrlKeyword(6);
        
        //登录用户创建
        if($userId) {
            $data = [
                'user_id'      => $userId,
                'keyword'      => $keyword,
                'link'         => $params['link'],
                'link_type'    => URL_LINK_TYPE_DEFAULT,
                'user_agent'   => $userAgent,
                'ip'           => $ip,
                'limit_clicks' => 0,
                'expire_time'  => date('Y-m-d H:i:s', strtotime('+20year')),
                'create_time'  => date('Y-m-d H:i:s')
            ];
            
        //游客创建 点击访问次数30次，过期时间为3天
        }else {
            $data = [
                'keyword'      => $keyword,
                'link'         => $params['link'],
                'link_type'    => URL_LINK_TYPE_DEFAULT,
                'user_agent'   => $userAgent,
                'ip'           => $ip,
                'limit_clicks' => 30,
                'expire_time'  => date('Y-m-d H:i:s', time() + 86400 * 3),
                'create_time'  => date('Y-m-d H:i:s')
            ];
        }
        $result = model('Url')->insertGetId($data);
        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
    
        $siteUrl = Env::get('app.short_url');
        return [
            'shortUrl' => $siteUrl.'/'.$keyword,
            'link'     => $params['link']
        ];
    }
    
}
